package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Speaker;
import com.qf.service.SpeakerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("speaker")
public class SpeakerController {

    @Autowired
    private SpeakerService speakerService;

    //分页展示主讲人
    @RequestMapping("showSpeakerList")
    public String showSpeakerList(Model model,
                                  @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                  @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        List<Speaker> speakerList = speakerService.findAll();

        PageInfo<Speaker> pageInfo = new PageInfo<>(speakerList);

        model.addAttribute("page", pageInfo);

        return "behind/speakerList.jsp";
    }

    //跳转到添加/修改主讲人界面
    @RequestMapping("addSpeaker")
    public String addSpeaker(Speaker speaker) {
        return "behind/addSpeaker.jsp";
    }

    //添加/修改主讲人
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Speaker speaker) {

        if (speaker.getId() == null) {
            speakerService.addSpeaker(speaker);
        } else {
            speakerService.update(speaker);
        }

        return "redirect:showSpeakerList";

    }

    //跳转到修改主讲人界面
    @RequestMapping("edit")
    public String edit(Integer id, Model model) {

        Speaker speaker = speakerService.findById(id);
        model.addAttribute("speaker", speaker);

        return "behind/addSpeaker.jsp";
    }

    //删除主讲人
    @RequestMapping("speakerDel")
    @ResponseBody
    public String speakerDel(Integer id) {
        speakerService.deleteSpeaker(id);

        Speaker speaker = speakerService.findById(id);

        if (speaker == null) {
            return "success";
        } else {
            return "false";
        }
    }
}
